import { message } from 'ant-design-vue'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useRequest } from 'vue-request'

import manualMessage from '@/components/ManualMessage'
import { LineFileInfo, LocalFileInfo } from '@/components/TaskList/types/index'
import useSetInterval from '@/hooks/useSetInterval'
import { dataCleaningApi, fetchDownload } from '@/services/api'
import { waitLoading } from '@/utils'
import PubSub from '@/utils/publish-subscribe'

export type TaskListOptions = {
  open: boolean
  key?: '1' | '2'
}

export const useTaskListDrawerStore = defineStore('taskListDrawer', () => {
  const pubSub = new PubSub<'changeTaskListDrawerOptions'>()

  const taskListOptions = ref<TaskListOptions>({
    open: false,
    key: '1'
  })

  const { start: lineRun, clear: lineStop } = useSetInterval()
  const { start: localRun, clear: localStop } = useSetInterval()
  const changeTaskListOptions = (options: TaskListOptions) => {
    taskListOptions.value.key = options.key || taskListOptions.value.key
    taskListOptions.value.open = options.open || false
    pubSub.publish('changeTaskListDrawerOptions', taskListOptions.value)

    lineStop()
    localStop()
    if (taskListOptions.value.open) {
      taskListOptions.value.key === '1' ? lineRun(getLineDataList, 1000 * 3, true) : localRun(getLocalDataList, 1000 * 3, true)
    } else {
      lineStop()
      localStop()
    }
  }

  /* ------------------------------------------- 在线导出 ----------------------------------------------- */
  const lineDataList = ref<LineFileInfo[]>([])
  const failedDataList = ref<LineFileInfo[]>([])
  const { runAsync: runOnlineExportCancel } = useRequest<ResponseData<any>>(dataCleaningApi.onlineExportCancel)
  const lineClearAll = async () => {
    const ids = lineDataList.value.map(item => item.id)
    if (ids.length === 0) return
    await runOnlineExportCancel({ exportIds: ids })
    getLineDataList()
  }
  const LineRemove = async (item: LineFileInfo) => {
    await runOnlineExportCancel({ exportIds: [item.id] })
    getLineDataList()
  }
  const { runAsync: runGetOnlineExportList } = useRequest<ResponseData<any>>(dataCleaningApi.onlineExportList)
  const statusMap: string[] = ['wait', 'uploading', 'successful', 'failed']
  /* 获取在线导出列表 */
  const getLineDataList = async () => {
    const { data } = await runGetOnlineExportList()
    lineDataList.value = data.map((item: any) => {
      return {
        id: item.exportId,
        name: item.exportName,
        address: `模型评估/${item.bucketName}`,
        progress: (item.handleNumber / item.totalNumber) * 100,
        message: `${item.failNumber}失败！`,
        status: statusMap[item.state],
        ...item
      }
    })
  }
  /* 获取失败列表 */
  const { runAsync: runGetOnlineExportFailedList } = useRequest<ResponseData<any>>(dataCleaningApi.onlineExportFailedList)
  const getFailedDataList = async (id: string) => {
    failedDataList.value = []
    const { data } = await runGetOnlineExportFailedList({}, { urlParams: { id } })
    failedDataList.value = data.map((item: any) => {
      return {
        id: item.bucketDataId,
        name: item.fileName
      }
    })
  }
  /* 重传 */
  const { runAsync: runOnlineExportTaskReset } = useRequest<ResponseData<any>>(dataCleaningApi.onlineExportTaskReset)
  const retransmission = async (id: string) => {
    await runOnlineExportTaskReset({}, { urlParams: { id } })
    getLineDataList()
  }

  /* ------------------------------------------- 本地导出 ----------------------------------------------- */
  const localDataList = ref<LocalFileInfo[]>([])
  const { runAsync: runLocalExportCancel } = useRequest<ResponseData<any>>(dataCleaningApi.localExportCancel)
  const localClearAll = async () => {
    const ids = localDataList.value.filter(item => item.status !== 0).map(item => item.id)
    if (ids.length === 0) return
    await runLocalExportCancel({ exportIds: ids })
    getLocalDataList()
  }
  const localRemove = async (item: LocalFileInfo) => {
    await runLocalExportCancel({ exportIds: [item.id] })
    getLocalDataList()
  }
  const { runAsync: runGetLocalExportList } = useRequest<ResponseData<any>>(dataCleaningApi.localExportList)
  const getLocalDataList = async () => {
    const { data } = await runGetLocalExportList()
    localDataList.value = data.map((item: any) => {
      return {
        id: item.exportId,
        name: item.exportName,
        location: `模型评估`,
        status: item.state,
        ...item
      }
    })
  }
  const localDownload = async (item: LocalFileInfo) => {
    const { data } = await dataCleaningApi.downloadExport({ id: item.id })

    try {
      waitLoading<ResponseData<any>>(fetchDownload(data.fileUrl, data.fileName), {
        loadingText: '数据准备中,请耐心等待...',
        errorText: '文件下载失败',
        successText: '文件下载成功'
      })
    } catch (error) {
      manualMessage.destroy()
      message.error({ content: '文件下载失败', key: 'downloading', duration: 2 })
    }
  }

  return {
    taskListOptions,
    changeTaskListOptions,
    lineDataList,
    failedDataList,
    localDataList,
    lineClearAll,
    LineRemove,
    localClearAll,
    localDownload,
    localRemove,
    pubSub,
    getFailedDataList,
    retransmission
  }
})
